// pages/components/tabbar/cart/index.js
var $ = getApp().globalData.eui;
var biz = require("../../../../biz.js");
$.component({
	/**
	 * 组件的属性列表
	 */
	properties: {

	},


	/**
	 * 组件的初始数据
	 */
	data: {
		"carts": [],
		"all": false,
		"addrid": 0,
		totalcount:0,
		"recvaddr": {},
		inEdit:false,
		$isPage:true,
		loginUser:getApp().globalData.loginUser
	},
	options: {
		addGlobalClass: true,
	},

	/**
	 * 组件的方法列表
	 */
	methods: {
		onSelRecvAddr: function (e) {
			var me = this;
			$.go("/pages/person/recvaddress/selrecvaddr");
		},
		onEdit:function(e){
			var me = this;
			me.setData({
				"inEdit" : !me.data.inEdit
			})
		},
		onCheck:function(e){
			var me = this;
			var index = $.toInt(e.currentTarget.dataset.index);
			var cart = me.data.carts[index];
			var checked = e.detail.value;
			var totalcount=0;

			var obj = {};

			//===更新选中状态
			cart.sel = checked;

			//===准备工作
			var tool = biz.CartTool.create();
			tool.Carts = me.data.carts;
			$.each(me.data.carts,function (c) {
				if( c.sel ) {
					tool.add(c.id,c.num);
					totalcount++;
				}
			});

			//===重新统计：小计、合计、运费、优惠券
			//匹配的优惠券
			cart.matchCoupons = tool.getMatchCoupons(cart.id);
			//运费
			cart.shipfee = tool.getShipFee(cart.id);
			//小计
			if(checked){
				cart.subtotal = tool.getSubTotal(cart.id);
			}

			//
			obj["carts"] = me.data.carts;
			//总价
			obj["totalprice"] = tool.getTotal();
			//是否全选
			obj["all"] = tool.isSelectedAll();
			//选中个数
			obj["totalcount"] = totalcount;

			me.setData(obj);

		},
		onNumChange:function(e){
			var me = this;
			var index = $.toInt(e.currentTarget.dataset.index);
			var num = $.toInt(e.detail.value);

			if (num >= 1) {
				var obj={};
				var cart = me.data.carts[index];

				cart.num = num;

				//===准备工作
				var tool = biz.CartTool.create();
				tool.Carts = me.data.carts;
				$.each(me.data.carts,function (c) {
					if( c.sel ) tool.add(c.id,c.num)
				});

				//===重新统计：小计、合计、运费、优惠券
				//匹配的优惠券
				cart.matchCoupons = tool.getMatchCoupons(cart.id);
				//运费
				cart.shipfee = tool.getShipFee(cart.id);
				//小计
				if(cart.sel){
					cart.subtotal = tool.getSubTotal(cart.id);
				}

				//
				obj["carts"] = me.data.carts;
				//总价
				obj["totalprice"] = tool.getTotal();
				//是否全选
				obj["all"] = tool.isSelectedAll();

				me.setData(obj);
			}
		},
		onCheckAll:function(e){
			var me = this;
			var sel = e.detail.value;


			$.each(me.data.carts, function (cart) {
				cart.sel = sel;
			});

			var obj={};

			//===准备工作
			var tool = biz.CartTool.create();
			tool.Carts = me.data.carts;
			$.each(me.data.carts,function (c) {
				if( sel ) tool.add(c.id,c.num)
			});

			//===重新统计：小计、合计、运费、优惠券
			$.each(me.data.carts,function (c) {
				if( c.sel ){
					//匹配的优惠券
					c.matchCoupons = tool.getMatchCoupons(c.id);
					//运费
					c.shipfee = tool.getShipFee(c.id);
					//小计
					c.subtotal = tool.getSubTotal(c.id);
				}
			});


			//
			obj["carts"] = me.data.carts;
			//总价
			obj["totalprice"] = tool.getTotal();
			//是否全选
			obj["all"] = sel;
			//选中个数
			obj["totalcount"] = (sel ? me.data.carts.length : 0);

			me.setData(obj);

		},

		onViewProduct:function(e){
			var me = this;
			var id = $.toInt(e.currentTarget.dataset.id);
			$.go("/pages/product/detail?id="+id)
		},

		onPay: function (e) {

			var me = this;

			if (!me.data.addrid) {
				$.errorBox("错误", "请选择收货地址", function () {
					$.go("/pages/person/recvaddress/selrecvaddr");
				});
				return;
			}

			var products = [];
			var carts = [];
			$.each(me.data.carts, function (cart) {
				if (cart.sel) {
					products.push({
						id: cart.productid,
						skuid: $.toInt(cart.skuid),
						num: cart.num,
						fromuser:cart.fromuser
					});
				}else{
					carts.push(cart);
				}
			});
			me.setData({"carts":carts});

			$.api("mall.Order.Add", {
				products: $.toJson(products),
				addrid: me.data.addrid
			})
				.then(function (value) {
					//订单创建成功，则删除购物车中的记录
					$.each(me.data.carts, function (cart) {
						if (cart.sel) {
							$.api("mall.Cart.Remove",{"id":cart.id}).then(function (value) {
								$.log("cart:"+cart.id+"removed")
							});
						}
					});

					//$.alertBox("提示","提交成功");
					$.api("mall.Order.Pay", {
						orderid: value
					})
						.then(function (value) {
							wx.requestPayment({
								'timeStamp': value.timeStamp,
								'nonceStr': value.nonceStr,
								'package': value.package,
								'signType': 'MD5',
								'paySign': value.paySign,
								'success': function (res) {
									$.alertBox("提示", "支付成功")
										.then(function () {
											$.back();
										})
								},
								'fail': function (res) {
									console.log("支付 res:" + $.toJson(res));
									//支付 res:{"err_code":"-1","err_desc":"调用支付JSAPI缺少参数: package","errMsg":"requestPayment:fail"}
									//$.errorBox("错误", "支付失败：" + res.errMsg + " 原因：" + res.err_desc);
									wx.showToast({
										title: '支付失败',
										icon: 'error',
										duration: 2000,
										success:function () {

										}
									})
								},
								'complete': function (res) {
									//$.back();
								}
							})
						});
				})

		},
		onRemoveBatch: function (e) {

			var me = this;

			$.confirmBox("询问", "确定要把选定的商品从购物车中移除？", function () {
				var products = [];
				var arr = [];
				$.each(me.data.carts, function (cart) {
					if (cart.sel) {
						products.push({
							id: cart.productid,
							skuid: $.toInt(cart.skuid),
							num: 1
						});
					} else {
						arr.push(cart);
					}
				});

				$.api("mall.Cart.RemoveBatch", {
					products: $.toJson(products)
				})
					.then(function (value) {

						me.setData({
							carts: arr
						});
						me.updateTotal();
					});
			});

		},

		updateTotal: function (isfromAll) {

			var me = this;
			var totalcount = 0;
			var totalprice = 0;
			var isall = true;
			var ppc = biz.ProductPriceCounter.create();

			$.each(me.data.carts,function (cart) {
				if( cart.sel ){
					var product={};
					product.id = cart.productid;
					product.saleprice = cart.saleprice;
					if( cart.sku && $.isObject(cart.sku)) product.sku = cart.sku;
					if( cart.shippingcost && $.isObject(cart.shippingcost)) product.shippingcost = cart.shippingcost;
					product.num = cart.num;
					product.coupons = cart.coupons;
					ppc.addProduct(product);
					//更新满足条件的优惠券信息
					cart.matchCoupons = ppc.getProductCoupons(cart.productid);
					//运费
					cart.shipfee = ppc.getProductShipFee(cart.productid);
				}else{
					isall = false;
				}

			});

			me.setData({
				carts: me.data.carts,
				totalcount: totalcount,
				totalprice: ppc.getTotalPrice()
			});
			if( !isfromAll ){
				me.setData({all: (isall && me.data.carts.length > 0)})
			}
		},
		//更新总价
		updateTotalPrice:function(){
			var me = this;
		},

		notifySelRecvAddress: function (addr) {

			var me = this;
			me.setData({
				addrid: addr.id,
				recvaddr: addr
			});
		},
		loadAll:function () {
			var me = this;
			var loginUser = getApp().globalData.loginUser;
			if( !(loginUser && loginUser.id)) return;
			
			$.api("mall.Cart.ListPage", {
				pageindex: 1,
				pagesize: 100
			}).then(function (value) {
				$.each(value.datas, function (data) {
					data.sel = 0;
					data.matchCoupons=[];
					data.subtotal = 0;
					var icon = data.icon;
					if (icon.indexOf("/") === 0) {
						icon = $.getConfig("server_url") + icon;
						data.icon = icon;
					}
				});
				me.setData({
					"carts": value.datas
				});
			});

			$.api("mall.RecvAddress.LoadDefault", {}).then(function (value) {
				if (value && $.isObject(value)) {
					me.setData({
						"addrid": value.id,
						"recvaddr": value
					});
				}
			});
		},
		notifyLogin:function (oUser) {
			var me = this;
			$.log("=========>收到Login事件："+$.toJson(oUser));
			me.setData({"loginUser":oUser});
			me.afterLogin();
		},
		afterLogin:function () {
			var me = this;
			var oUser = me.data.loginUser;
			if( oUser && oUser.id ){
				me.loadAll();
			}
		},
		onScan:function (e) {
			wx.reLaunch({
				url: '/pages/index',
			})
		}
	},
	lifetimes: {
		attached: function () {
			var me = this;
			getApp().getLoginUser(function (oUser) {
				me.setData({"loginUser":oUser});
				me.afterLogin();
			})
		},
		detached: function () {
			// 在组件实例被从页面节点树移除时执行
		},
	},
})
